/**
 * 文件下载通用方法
 * @param {string} url - 请求URL
 * @param {object} data - 请求数据
 * @param {object} options - 请求配置选项
 * @returns {Promise<{success: boolean, message: string, data: any}>} - 下载结果
 */
const downloadFile = async (url, data, options = {}) => {
    try {
        const defaultOptions = {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {
                'Content-Type': 'application/json'
            }
        };
        
        const requestOptions = { ...defaultOptions, ...options };
        const response = await fetch(url, requestOptions);
        
        if (!response.ok) {
            return {
                success: false,
                message: `HTTP error! status: ${response.status}`,
                data: { status: response.status }
            };
        }
        
        const contentType = response.headers.get('content-type');
        const contentDisposition = response.headers.get('content-disposition');
        
        // 检查是否为文件流响应
        const validContentTypes = [
            'application/octet-stream', 
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ];
        
        if (!contentDisposition || 
            !(contentType && validContentTypes.some(type => contentType.includes(type)))) {
            try {
                const clonedResponse = response.clone();
                const responseData = await clonedResponse.json();
                
                return {
                    success: false,
                    message: responseData?.m || "非文件流响应",
                    data: responseData
                };
            } catch (parseError) {
                const textContent = await response.text();
                return {
                    success: false,
                    message: textContent || '下载失败，无法解析服务器响应',
                    data: null
                };
            }
        }
        
        // 解析文件名
        let filename = '';
        if (contentDisposition) {
            const filenameMatch = contentDisposition.match(/filename=(.+)/);
            if (filenameMatch && filenameMatch[1]) {
                filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
            }
        }
        
        // 下载文件
        const blob = await response.blob();
        const fileUrl = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = fileUrl;
        a.download = filename || 'download';
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(fileUrl);
        document.body.removeChild(a);
        
        return {
            success: true,
            message: '下载成功',
            data: { filename }
        };
    } catch (error) {
        console.error('下载失败:', error);
        return {
            success: false,
            message: error.message || '下载失败',
            data: error
        };
    }
};

export default downloadFile;